﻿using System;
using System.Reflection;
using System.Threading;
using CatEars.Core.Console;

namespace CatEars.Core.Utility
{
    /// <summary>
    /// 进程单例
    /// </summary>
    public static class SingletonProcess
    {
        /// <summary>
        /// 进程单例运行
        /// </summary>
        /// <param name="mutexKey">互斥key</param>
        /// <returns>true 已经有一个实例启动</returns>
        public static bool CheckByMutex(string mutexKey)
        {
            if(mutexKey == null)
            {
                mutexKey = Assembly.GetEntryAssembly().FullName;
            }
            bool createdNew = false;
            Mutex mutex = new Mutex(true, mutexKey, out createdNew);
            return !createdNew;
        }

        /// <summary>
        /// 限制程序单例运行
        /// </summary>
        /// <param name="mutexKey">互斥key</param>
        /// <param name="autoExit">自动退出程序</param>
        /// <param name="displayMode">0无提示 1-Console提示 2-mbox(wf)提示 3-mbox(wpf)提示</param>
        /// <param name="tipText">提示内容 null则使用默认提示</param>
        /// <returns>true 已经有一个实例启动</returns>
        public static bool CheckByMutex(string mutexKey,
            bool autoExit, int displayMode, string tipText = null)
        {
            if (!CheckByMutex(mutexKey))
            {
                return false;
            }
            if (string.IsNullOrEmpty(tipText))
            {
                tipText = "当前程序只能启动一个实例。";
                if (autoExit)
                {
                    tipText = tipText + AppDefine.NewLine + AppDefine.NewLine + "程序即将退出。";
                }
            }
            switch (displayMode)
            {
                case 1:
                    ColorConsole.WriteError(tipText);
                    break;
                case 2:
                    System.Windows.Forms.MessageBox.Show(tipText, "提示",
                        System.Windows.Forms.MessageBoxButtons.OK,
                        System.Windows.Forms.MessageBoxIcon.Information);
                    break;
                case 3:
                    System.Windows.MessageBox.Show(tipText, "提示",
                        System.Windows.MessageBoxButton.OK,
                        System.Windows.MessageBoxImage.Information);
                    break;
            }
            if (autoExit) { Environment.Exit(1); }
            return true;
        }
    }
}
